<?php


namespace Yond\LaravelDomain\Console\Traits;

use Yond\LaravelDomain\Console\Command;

/**
 * Trait ParserTrait
 * @mixin Command
 */
trait ParserTrait
{
    /**
     * replaces the variables in the path structure with defined values
     *
     * @param $pathStructure
     * @param $data
     *
     * @return mixed
     */
    public function parsePath($pathStructure, $data)
    {
        return base_path(str_replace(array_map([$this, 'maskPathVariables'], array_keys($data)), array_values($data), $pathStructure));
    }

    /**
     * replaces the variables in the stub file with defined values
     *
     * @param $stub
     * @param $data
     *
     * @return mixed
     */
    public function parseStubContent($stub, $data)
    {
        return str_replace(array_map([$this, 'maskStubVariables'], array_keys($data)), array_values($data), $stub);
    }


    protected function getStub($stubName): string
    {
        $stubFile = $this->resolveStubPath($stubName);
        return $stubFile ? $this->files->get($stubFile) : '';
    }

    protected function resolveStubPath(string $stub): string
    {
        return file_exists($customPath = $this->laravel->basePath('stubs/' . trim($stub, '/')))
            ? $customPath
            : __DIR__ . '/../../../stubs/default/' .trim($stub, '/');
    }

    private function maskPathVariables($key): string
    {
        return '{' . $key . '}';
    }

    private function maskStubVariables($key): string
    {
        return '{{' . $key . '}}';
    }

}